package org.test.transaction;

import com.sun.xml.internal.bind.v2.model.runtime.RuntimeNonElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by Hy on 2018/7/11.
 * 数据库操作助手类
 */
public final class DatabaseHelper {
    //数据库配置
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/demo";
    private static final String username = "root";
    private static final String password = "admin";
    private static final Logger logger = LoggerFactory.getLogger(DatabaseHelper.class);

    /**
     * 定义一个局部线程变量
     */
    private static final ThreadLocal<Connection> connContainer = new ThreadLocal<Connection>();
 //   {
//        @Override
//        protected Connection initialValue() {
//            try {
//                Class.forName(driver);
//                return DriverManager.getConnection(url,username,password);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return null;
//        }
//    };

    /**
     * 开启事务
     */
    public static void beginTransaction(){
        Connection conn = connContainer.get();
        if(conn!=null){
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                logger.error("begin transaction failture",e);
                throw new RuntimeException(e);
            }finally{
                connContainer.set(conn);
            }
        }
    }

    /**
     * 提交事务
     */
    public static void commitTransaction(){
        Connection conn = connContainer.get();
        if(conn!=null){
            try {
                conn.commit();
                conn.close();
            } catch (SQLException e) {
                logger.error("commit transaction failure",e);
                throw new RuntimeException(e);
            }finally{
                connContainer.remove();
            }
        }
    }
    /**
     * 回滚事务
     */
    public static void rollbackTransaction(){
        Connection conn = connContainer.get();
        if(conn!=null){
            try {
                conn.rollback();
                conn.close();
            } catch (SQLException e) {
                logger.error("rollback transaction failure",e);
                throw new RuntimeException(e);
            }finally{
                connContainer.remove();
            }
        }
    }
}
